package com.yanyu.space.sys.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.code.kaptcha.Producer;
import com.yanyu.space.common.auth.support.AuthUtil;
import com.yanyu.space.common.auth.bean.enums.AuthType;
import com.yanyu.space.common.core.bean.auth.SpaceUser;
import com.yanyu.space.common.core.exception.ServiceException;
import com.yanyu.space.common.core.bean.web.R;
import com.yanyu.space.sys.bean.po.User;
import com.yanyu.space.sys.bean.vo.login.LoginInfoVo;
import com.yanyu.space.sys.bean.vo.login.LoginSearchVo;
import com.yanyu.space.sys.bean.vo.login.RouterVo;
import com.yanyu.space.sys.bean.enums.EnabledEnum;
import com.yanyu.space.sys.bean.enums.SysRedisKeyEnum;
import com.yanyu.space.sys.bean.enums.SysRCode;
import com.yanyu.space.sys.service.IMenuService;
import com.yanyu.space.sys.service.IRoleService;
import com.yanyu.space.sys.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("/sys")
@Api(tags = "系统登录")
@AllArgsConstructor
public class LoginController {

    private IUserService userService;
    private IMenuService menuService;
    private IRoleService roleService;
    private Producer producer;
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation(value = "生成验证码")
    @GetMapping("/captchaImage")
    public R<LoginInfoVo> genImagecode() {
        // 生成文字验证码
        String text = producer.createText();

        //生成图片验证码
        BufferedImage image = producer.createImage(text);

        //保存 redis key 自己设置
        String uuid = StringUtils.replaceChars(UUID.randomUUID().toString(), "-", "");
        stringRedisTemplate.opsForValue().set(SysRedisKeyEnum.IMAGECODE.getCode(uuid), text, SysRedisKeyEnum.IMAGECODE.getTimeOut(5), SysRedisKeyEnum.IMAGECODE.getUnit());
        log.info("生成验证码，请求[{}],验证码[{}]", uuid, text);

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "jpg", baos);
            LoginInfoVo vo = new LoginInfoVo();
            vo.setUuid(uuid);
            vo.setImg(Base64.getEncoder().encodeToString(baos.toByteArray()));
            return R.ok(vo);
        } catch (Exception e) {
            return R.fail();
        }
    }

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public R<Map> login(@RequestBody @Valid LoginSearchVo vo) {
        String repImageCode = stringRedisTemplate.opsForValue().get(SysRedisKeyEnum.IMAGECODE.getCode(vo.getUuid()));
        if (StringUtils.isBlank(repImageCode) || !repImageCode.equalsIgnoreCase(vo.getCode())) {
            throw new ServiceException(SysRCode.LOGIN_IMAGECODE_ERROR);
        }

        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUserName, vo.getUsername()));
        if (user == null) {
            throw new ServiceException(SysRCode.LOGIN_ACCOUNT_ERROR);
        }
        if (!user.getPassword().equals(vo.getPassword())) {
            throw new ServiceException(SysRCode.LOGIN_ACCOUNT_ERROR);
        }
        if (EnabledEnum.NO.match(user.getEnabled())) {
            throw new ServiceException(SysRCode.LOGIN_ACCOUNT_DISABLED);
        }

        SpaceUser spaceUser = SpaceUser.builder().id(user.getId())
                .userName(user.getUserName()).deptId(user.getDeptId())
                .sysFlag(user.getSysFlag()).avatar(user.getAvatar()).build();
        AuthUtil.login(spaceUser, AuthType.ADMIN_TYPE);
        return R.newMap().put("token", StpUtil.getTokenValue()).build();
    }

    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/getInfo")
    public R<Map> getInfo() {
        SpaceUser spaceUser = AuthUtil.getSession(AuthType.ADMIN_TYPE);
        StpUtil.getSession().get("test", spaceUser);
        R.Builder builder = R.newMap().put("user", spaceUser);
        if (spaceUser.isAdmin()) {
            builder.put("roles", Arrays.asList("admin"));
            builder.put("permissions", Arrays.asList("*:*:*"));
        } else {
            Set<String> roleCodes = roleService.listAllocated(spaceUser.getId());
            builder.put("roles", roleCodes);
            Set<String> menuPerms = menuService.listAllocated(spaceUser.getId());
            builder.put("permissions", menuPerms);
        }
        return builder.build();
    }

    @ApiOperation(value = "退出")
    @PostMapping("/logout")
    public R logout() {
        StpUtil.logout();
        return R.ok();
    }

    @ApiOperation(value = "获取路由信息")
    @GetMapping("/getRouters")
    public R<List<RouterVo>> getRouters() {
        List<RouterVo> vos = menuService.getRouters();
        return R.ok(vos);
    }
}
